// 投诉建议页面逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 页面元素
    const problemDesc = document.getElementById('problemDesc');
    const fileUpload = document.getElementById('fileUpload');
    const uploadedFilesContainer = document.getElementById('uploadedFilesContainer');
    const categoryGrid = document.getElementById('categoryGrid');
    const phoneInput = document.getElementById('phoneInput');
    const submitBtn = document.getElementById('submitBtn');
    const successModal = document.getElementById('successModal');
    const modalBtn = document.getElementById('modalBtn');
    
    // 页面数据
    let data = {
        problemDesc: '',
        images: [],
        categories: [
            '设施损坏', '环境卫生', '噪音扰民',
            '安全隐患', '服务态度', '绿化问题',
            '灯光问题', '停车缴费', '球场退费',
            '游客不良行为', '其他'
        ],
        selectedCategory: null,
        gender: 'male',
        phone: ''
    };
    
    // 初始化类别列表
    function initCategories() {
        data.categories.forEach((category, index) => {
            const div = document.createElement('div');
            div.className = 'category-item';
            div.textContent = category;
            div.dataset.index = index;
            div.addEventListener('click', function() {
                selectCategory(index);
            });
            categoryGrid.appendChild(div);
        });
    }
    
    // 选择投诉类别
    function selectCategory(index) {
        data.selectedCategory = index;
        
        // 更新UI
        const items = document.querySelectorAll('.category-item');
        items.forEach((item, i) => {
            if (i === index) {
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
        });
    }
    
    // 处理文件上传
    function handleFileUpload(e) {
        const files = e.target.files;
        if (!files || files.length === 0) return;
        
        // 检查文件数量
        if (data.images.length + files.length > 3) {
            alert('最多上传3个文件');
            return;
        }
        
        // 处理每个文件
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();
            
            reader.onload = function(e) {
                data.images.push({
                    url: e.target.result,
                    name: file.name
                });
                updateUploadedFiles();
            };
            
            if (file.type.startsWith('image/')) {
                reader.readAsDataURL(file);
            } else if (file.type.startsWith('video/')) {
                reader.readAsDataURL(file);
            }
        }
        
        // 重置input，允许重复选择同一文件
        fileUpload.value = '';
    }
    
    // 更新已上传文件显示
    function updateUploadedFiles() {
        uploadedFilesContainer.innerHTML = '';
        
        data.images.forEach((file, index) => {
            const div = document.createElement('div');
            div.className = 'uploaded-item';
            
            const isVideo = file.name.includes('.mp4') || file.name.includes('.mov') || file.name.includes('.avi');
            
            const img = document.createElement('img');
            img.className = 'uploaded-media';
            img.src = isVideo ? 'images/video-icon.png' : file.url;
            img.alt = file.name;
            img.dataset.index = index;
            img.addEventListener('click', function() {
                previewFile(index);
            });
            
            const deleteBtn = document.createElement('div');
            deleteBtn.className = 'delete-btn';
            deleteBtn.textContent = '×';
            deleteBtn.dataset.index = index;
            deleteBtn.addEventListener('click', function() {
                deleteFile(index);
            });
            
            div.appendChild(img);
            div.appendChild(deleteBtn);
            uploadedFilesContainer.appendChild(div);
        });
    }
    
    // 预览文件
    function previewFile(index) {
        const file = data.images[index];
        if (!file) return;
        
        const isVideo = file.name.includes('.mp4') || file.name.includes('.mov') || file.name.includes('.avi');
        
        if (isVideo) {
            // 视频预览
            const videoPreview = document.createElement('video');
            videoPreview.src = file.url;
            videoPreview.controls = true;
            videoPreview.style.maxWidth = '90%';
            videoPreview.style.maxHeight = '90%';
            
            const previewModal = document.createElement('div');
            previewModal.style.position = 'fixed';
            previewModal.style.top = '0';
            previewModal.style.left = '0';
            previewModal.style.right = '0';
            previewModal.style.bottom = '0';
            previewModal.style.backgroundColor = 'rgba(0,0,0,0.8)';
            previewModal.style.display = 'flex';
            previewModal.style.alignItems = 'center';
            previewModal.style.justifyContent = 'center';
            previewModal.style.zIndex = '1001';
            previewModal.appendChild(videoPreview);
            
            previewModal.addEventListener('click', function() {
                document.body.removeChild(previewModal);
            });
            
            document.body.appendChild(previewModal);
        } else {
            // 图片预览
            const imgPreview = document.createElement('img');
            imgPreview.src = file.url;
            imgPreview.style.maxWidth = '90%';
            imgPreview.style.maxHeight = '90%';
            
            const previewModal = document.createElement('div');
            previewModal.style.position = 'fixed';
            previewModal.style.top = '0';
            previewModal.style.left = '0';
            previewModal.style.right = '0';
            previewModal.style.bottom = '0';
            previewModal.style.backgroundColor = 'rgba(0,0,0,0.8)';
            previewModal.style.display = 'flex';
            previewModal.style.alignItems = 'center';
            previewModal.style.justifyContent = 'center';
            previewModal.style.zIndex = '1001';
            previewModal.appendChild(imgPreview);
            
            previewModal.addEventListener('click', function() {
                document.body.removeChild(previewModal);
            });
            
            document.body.appendChild(previewModal);
        }
    }
    
    // 删除文件
    function deleteFile(index) {
        data.images.splice(index, 1);
        updateUploadedFiles();
    }
    
    // 设置性别
    function setGender(e) {
        data.gender = e.target.value;
    }
    
    
    // 提交
    function submit() {
        // 获取表单数据
        data.problemDesc = problemDesc.value.trim();
        data.phone = phoneInput.value.trim();
        
        // 表单验证
        if (!data.problemDesc) {
        alert('请填写问题描述');
        return;
        }
        
        if (data.selectedCategory === null) {
        alert('请选择投诉类别');
        return;
        }
        
        // 新增手机号码格式验证
        const phoneReg = /^1[3-9]\d{9}$/;
        if (!data.phone) {
        alert('请填写手机号码');
        return;
        } else if (!phoneReg.test(data.phone)) {
        alert('请填写正确的11位手机号码');
        return;
        }
        
        // 显示成功模态框
        successModal.style.display = 'flex';
        
        // 提交逻辑
        console.log('提交的数据:', data);
    }
    
    // 隐藏模态框
    function hideModal() {
        successModal.style.display = 'none';
        // 返回上一页
        window.location.href = '../main-map/main.html';
    }
    
    // 手机号输入过滤 - 只允许输入数字
    function filterPhoneInput(e) {
        // 只允许输入数字和退格、删除、方向键等控制键
        if (!/^\d$/.test(e.key) && 
            !['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(e.key)) {
            e.preventDefault();
        }
        
        // 实时显示输入长度提示
        const currentLength = e.target.value.length;
        if (currentLength >= 11 && e.key !== 'Backspace' && e.key !== 'Delete') {
            e.preventDefault();
        }
    }

    // 绑定事件
    fileUpload.addEventListener('change', handleFileUpload);
    submitBtn.addEventListener('click', submit);
    modalBtn.addEventListener('click', hideModal);
    
    // 绑定性别选择事件
    const genderRadios = document.querySelectorAll('input[name="gender"]');
    genderRadios.forEach(radio => {
        radio.addEventListener('change', setGender);
    });
    
    // 绑定手机号输入过滤事件
    phoneInput.addEventListener('keydown', filterPhoneInput);
    
    // 初始化
    initCategories();
});
